/**
 * 登录
 */
import * as api from '@/services/base/global';

function recursionData(data, arrList) {
  for (let i = 0; i < data.length; i++) {
    arrList.push(data[i]);
    if (data[i]['child'] && data[i].level < 2) {
      recursionData(data[i]['child'], arrList);
    }
  }
}

function getOption(data, arr) {
  for (let i = 0; i < data.length; i++) {
    arr.push({ ...data[i], chil: null });
    if (data[i]['child']) {
      getOption(data[i]['child'], arr);
    }
  }
}

export default {
  namespace: 'base_global',

  state: {
    dictList: [],
    allIndustry: [],
  },

  effects: {
    *getNewChinaAreaSel({ payload }, { call, put }) {
      const { deptId, type } = payload;
      const { data, code } = yield call(api.getNewChinaAreaSel, payload);
      let newData = [];
      if (data) {
        newData = data.filter((item) => {
          const { code, parentId } = item;
          if (deptId && deptId !== 100000) {
            return parseInt(code) == deptId || parseInt(parentId) == deptId;
          } else {
            return item;
          }
        });
      }
      return newData;
    },

    *getDictList({ payload }, { call, put }) {
      const { data, code } = yield call(api.getDictList, payload);
      let result = [];
      if (code && code == 200) {
        result = data || [];
      }
      return result;
    },

    *getAllIndustry({ payload }, { call, put }) {
      const { data, code } = yield call(api.getAllIndustry, payload);
      let result = [];
      if (code && code == 200) {
        result = data || [];
      }
      return result;
    },

    *getCountryAll({ payload }, { call, put }) {
      const { data, code } = yield call(api.getCountryAll, payload);
      let result = [];
      if (code && code == 200) {
        result = data || [];
      }
      return result;
    },

    // 获取区域下拉
    *getChinaAreaSel({ payload }, { call, put }) {
      const { data, code } = yield call(api.getChinaAreaSel, payload);
      let arrList = [];
      if (code == 200) {
        recursionData(data || [], arrList);
        yield put({
          type: 'saveState',
          payload: {
            areaOption: arrList || [],
          },
        });
      }
      return arrList || [];
    },

    /** 世界区域下拉 */
    *getWordAreaSel({ payload }, { call, put }) {
      const { data, code } = yield call(api.getWordAreaSel, payload);
      let arrList = [];
      if (code == 200) {
        if (data) {
          getOption(data, arrList);
        }
        yield put({
          type: 'saveState',
          payload: {
            wordOption: arrList || [],
          },
        });
      }
      return arrList || [];
    },
  },

  reducers: {
    saveState(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};
